package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    WorkspaceService workspaceService;

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        if (begin.isAfter(end)) {
            return null;
        }
        //list用于存放从begin到end的所有日期
        List<LocalDate> list = new ArrayList<>();
        LocalDate date = begin;
        while (date.isBefore(end)) {
            list.add(date);
            date = date.plusDays(1);
        }
        list.add(end);
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setDateList(StringUtils.join(list, ","));

        //存放每天的营业额
        List<Double> dataList = new ArrayList<>();
        for (LocalDate localDate : list) {
            //一天的起始时间和结束时间
            LocalDateTime minTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime maxTime = LocalDateTime.of(localDate, LocalTime.MAX);

            HashMap map = new HashMap();
            map.put("begin", minTime);
            map.put("end", maxTime);
            map.put("status", Orders.COMPLETED);
            Double sum = orderMapper.sumByMap(map);
            if (sum == null) {
                sum = 0d;
            }
            dataList.add(sum);
        }
        turnoverReportVO.setTurnoverList(StringUtils.join(dataList, ","));
        return turnoverReportVO;
    }

    /**
     * 用户统计
     *
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //判断日期是否有误
        if (begin.isAfter(end)) {
            return null;
        }

        //将日期封装进vo
        List<LocalDate> list = new ArrayList<>();
        LocalDate date = begin;
        while (date.isBefore(end)) {
            list.add(date);
            date = date.plusDays(1);
        }
        list.add(end);

        List<Integer> newUserList = new ArrayList<>();
        List<Integer> userList = new ArrayList<>();
        for (LocalDate localDate : list) {
            LocalDateTime minTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime maxTime = LocalDateTime.of(localDate, LocalTime.MAX);
            HashMap map = new HashMap();

            //查找总用户数量
            map.put("end", maxTime);
            Integer sumUser = userMapper.countByMap(map);
            userList.add(sumUser);

            //查找当天新增用户数量
            map.put("begin", minTime);
            Integer sumNewUser = userMapper.countByMap(map);
            newUserList.add(sumNewUser);
        }

        return UserReportVO.builder()
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(userList, ","))
                .dateList(StringUtils.join(list, ","))
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //判断日期是否有误
        if (begin.isAfter(end)) {
            return null;
        }
        OrderReportVO userReportVO = new OrderReportVO();

        //将日期封装进vo
        List<LocalDate> dateList = new ArrayList<>();
        LocalDate date = begin;
        while (date.isBefore(end)) {
            dateList.add(date);
            date = date.plusDays(1);
        }
        dateList.add(end);

        List<Integer> countOrderList = new ArrayList<>();
        List<Integer> validCountOrderList = new ArrayList<>();
        //遍历查询每天的有效订单数和订单总数
        for (LocalDate localDate : dateList) {
            LocalDateTime minTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime maxTime = LocalDateTime.of(localDate, LocalTime.MAX);
            HashMap map = new HashMap();
            map.put("begin", minTime);
            map.put("end", maxTime);
            //查询当天订单总数
            Integer countOrder = orderMapper.countByMap(map);
            countOrderList.add(countOrder);

            //查询当天有效订单数
            map.put("status", Orders.COMPLETED);
            Integer validCountOrder = orderMapper.countByMap(map);
            validCountOrderList.add(validCountOrder);
        }

        //计算时间区间内的订单总数
        Integer totalCountOrder = countOrderList.stream().reduce(Integer::sum).get();

        //计算时间区间内的有效订单数
        Integer validCountOrder = validCountOrderList.stream().reduce(Integer::sum).get();

        //计算订单完成率
        Double orderCompletionRate = 0.0;
        if (totalCountOrder != 0) {
            orderCompletionRate = validCountOrder.doubleValue() / totalCountOrder;
        }

        OrderReportVO vo = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .validOrderCountList(StringUtils.join(validCountOrderList, ","))
                .orderCountList(StringUtils.join(countOrderList, ","))
                .orderCompletionRate(orderCompletionRate)
                .validOrderCount(validCountOrder)
                .totalOrderCount(totalCountOrder)
                .build();

        return vo;
    }

    /**
     * 销量排名top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        LocalDateTime minTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime maxTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> top10 = orderMapper.getSalesTop10(minTime, maxTime);
        List<String> nameList = top10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = top10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO
                .builder()
                .numberList(StringUtils.join(numberList,","))
                .nameList(StringUtils.join(nameList,","))
                .build();
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //1.查询数据库获取营业数据--查询最近30天的运营数据
        LocalDate beginDay = LocalDate.now().minusDays(30);
        LocalDate endDay = LocalDate.now().minusDays(1);
        LocalDateTime begin = LocalDateTime.of(beginDay, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(endDay, LocalTime.MAX);
        BusinessDataVO data = workspaceService.getBusinessData(begin, end);

        //2.通过POI将数据写入excel文件
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于模板文件创建一个新的excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //获取表格文件sheet页
            XSSFSheet sheet = excel.getSheet("sheet1");
            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + beginDay + "至" + endDay);
            //获取第四行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(data.getTurnover());
            row.getCell(4).setCellValue(data.getOrderCompletionRate());
            row.getCell(6).setCellValue(data.getNewUsers());
            //获取第五行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(data.getValidOrderCount());
            row.getCell(4).setCellValue(data.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = beginDay.plusDays(i);
                LocalDateTime minTime = LocalDateTime.of(date, LocalTime.MIN);
                LocalDateTime maxTime = LocalDateTime.of(date, LocalTime.MAX);
                //查询某一天的营业数据
                BusinessDataVO dataEveryday = workspaceService.getBusinessData(minTime, maxTime);
                //当天的数据所在的行数
                XSSFRow rowEveryday = sheet.getRow(7 + i);
                rowEveryday.getCell(1).setCellValue(date.toString());
                rowEveryday.getCell(2).setCellValue(dataEveryday.getTurnover());
                rowEveryday.getCell(3).setCellValue(dataEveryday.getValidOrderCount());
                rowEveryday.getCell(4).setCellValue(dataEveryday.getOrderCompletionRate());
                rowEveryday.getCell(5).setCellValue(dataEveryday.getUnitPrice());
                rowEveryday.getCell(6).setCellValue(dataEveryday.getNewUsers());
            }

            //3.通过输出流将excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
